package 算法.leetcode.bytedance;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author lchenglong
 * @date 2022/5/14
 */
public class OfferArray_VIIII {

    public static void main(String[] args) {
        OfferArray_VIIII instance = new OfferArray_VIIII();
        int[][] intervals = new int[][]{{2,4},{5,5},{8,9},{1,10}};
        int[][] ans = instance.merge(intervals);
        System.out.println(Arrays.toString(ans));
    }
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o1[0]-o2[0];
            }
        });
        List<int[]> ans = new ArrayList<>();
        for (int i=0;i<intervals.length;i++) {
            int l = intervals[i][0],r = intervals[i][1];
            if (ans.size() == 0|| ans.get(ans.size()-1)[1]<l){
                ans.add(new int[]{l,r});
            } else {
                ans.get(ans.size()-1)[1] = Math.max(ans.get(ans.size()-1)[1],r);
            }
        }
        return ans.toArray(new int[ans.size()][2]);
    }

    // 数字轴,没搞定
    public int[][] merge2(int[][] intervals) {
        int max=0,min = 10001;
        for (int i=0;i<intervals.length;i++) {
            min = Math.min(intervals[i][0],min);
            max = Math.max(intervals[i][1],max);
        }
        byte[] bits = new byte[max-min+2];
        for (int i=0;i<intervals.length;i++) {
            if (intervals[i][0]==intervals[i][1]){
                bits[intervals[i][0]] = 1;
                continue;
            }
            for (int j = intervals[i][0];j<intervals[i][1];j++){
                bits[j]=1;
            }
        }
        List<int[]> ansList = new ArrayList<>();
        int flag =0;
        for (int i=0;i<bits.length;i++) {
            if (flag == 0 && bits[i]==1){
                ansList.add(new int[]{i,0});
                flag = 1;
            } else if (flag == 1 && bits[i]==0){
                int[] interval = ansList.get(ansList.size() - 1);
                interval[1] = i;
                ansList.set(ansList.size()-1,interval);
                flag = 0;
            }
        }
        int[][] ans = ansList.toArray(new int[ansList.size()][2]);
        return ans;

    }
}
